<template>
  <px-dialog v-model="visible" class="tool-dialog" title="工具报废处理" width="800px" @open="openDialog" @close="closeDialog">
    <div class="tool-dialog-content">
      <px-form ref="formRef" class="tool-dialog-form" :inline="true" :model="formValue" :rules="rules" label-position="right" label-width="120px">
        <px-form-item label="报废人" prop="scrapBy">
          <px-select-v2 v-model="formValue.scrapBy" filterable clearable :options="scrapByList" placeholder="请选择报废人" @change="scrapByChange" />
        </px-form-item>
        <px-form-item label="报废原因" prop="scrapReason">
          <px-select v-model="formValue.scrapReason" placeholder="请选择报废原因" maxlength="50" filterable clearable>
            <px-option v-for="item in scrapReasonList" :key="item.id" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-form-item label="备注" prop="scrapRemark">
          <px-input
            v-model="formValue.scrapRemark"
            type="textarea"
            placeholder="请输入备注"
            maxlength="1000"
            :autosize="{ minRows: 2, maxRows: 4 }"
          />
        </px-form-item>
        <px-form-item label="上传图片" prop="checkPic">
          <PhotoUpload
            v-if="visible"
            photoType="add"
            :photoData="{ moduleName: moduleName }"
            :photoList="formValue.checkPic"
            @changePhotoList="changePhotoList"
            @savePhotoStatus="savePhotoStatus"
          />
        </px-form-item>
        <px-form-item label="第三方检测报告" prop="checkReportList">
          <DialogFileUpload
            v-if="visible"
            :fileData="{ moduleName: moduleName }"
            fileTitle="报告"
            @changeFileList="changeFileList"
            @saveFileStatus="saveFileStatus"
          />
        </px-form-item>
      </px-form>
      <div style="margin-top: 16px; text-align: right">
        <px-button @click="closeDialog">取消</px-button>
        <px-button type="primary" :disabled="photoStatusFlag || fileStatusFlag" @click="handleSubmit(formRef)">确认</px-button>
      </div>
    </div>
  </px-dialog>
</template>
<script setup lang="ts">
import { queryDictData } from "@/api/common";
import { getModuleName, scrapToolLedger } from "@/api/equip/toolManage";
import DialogFileUpload from "@/components/Upload/DialogFileUpload.vue";
import PhotoUpload from "@/components/Upload/PhotoUpload.vue";
import { getToken } from "@/utils/auth";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import { PxMessage } from "px-ui";
import { computed, getCurrentInstance, reactive, toRefs } from "vue";

// 调用父级-查询主页列表、关闭弹窗方法
const emits = defineEmits(["queryTable", "closeDialog"]);
// 父级传过来的值
const props = defineProps({
  // 控制弹窗显示隐藏
  visible: {
    type: Boolean,
    default: false
  },
  // 工具台账id
  toolId: {
    type: Number,
    default() {
      return undefined;
    }
  }
});
const visible = computed(() => props.visible);
// 页面本身的值
const { proxy }: any = getCurrentInstance();
const state = reactive<any>({
  formRef: null,
  formValue: {
    scrapBy: null,
    scrapName: "",
    scrapReason: "",
    scrapRemark: "",
    checkPic: [],
    checkReportList: []
  },
  scrapByList: [],
  scrapReasonList: [],
  headers: {
    Authorization: "Bearer " + getToken().accessToken || ""
  },
  moduleName: "",
  photoStatusFlag: false,
  fileStatusFlag: false
});
const { formRef, formValue, scrapByList, scrapReasonList, headers, moduleName, photoStatusFlag, fileStatusFlag } = toRefs(state);
const rules = computed(() => ({
  scrapBy: [{ required: true, message: "报废人不能为空", trigger: ["blur", "change"] }],
  scrapReason: [{ required: true, message: "报废原因不能为空", trigger: ["blur", "change"] }]
}));
// 获取报废原因
const queryScrapReasonSelect = async () => {
  scrapReasonList.value = [];
  const params = {
    typeCode: "scrapReason"
  };
  const data = await queryDictData(params);
  scrapReasonList.value = data;
};
// 获取报废人名称
const scrapByChange = val => {
  const arr = scrapByList.value.filter(item => {
    return item.value === val;
  });
  if (arr && arr.length > 0) {
    formValue.value.scrapName = arr[0].label;
  }
};
// 新的图片列表
const changePhotoList = val => {
  formValue.value.checkPic = val;
};
// 图片是否上传完，是否可以保存
const savePhotoStatus = val => {
  photoStatusFlag.value = val;
};
// 新的报告列表
const changeFileList = val => {
  formValue.value.checkReportList = val;
};
// 文件是否上传完，是否可以保存
const saveFileStatus = val => {
  fileStatusFlag.value = val;
};

// 提交-确定工具报废
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const checkPic = [];
      if (formValue.value.checkPic && formValue.value.checkPic.length > 0) {
        formValue.value.checkPic.forEach(item => {
          if (item?.id) {
            checkPic.push(item.id);
          } else if (item?.response.data.id) {
            checkPic.push(item.response.data.id);
          }
        });
      }
      const checkReportList = [];
      if (formValue.value.checkReportList && formValue.value.checkReportList.length > 0) {
        formValue.value.checkReportList.forEach(item => {
          if (item?.id) {
            checkReportList.push(item.id);
          } else if (item?.response.data.id) {
            checkReportList.push(item.response.data.id);
          }
        });
      }
      const params = {
        id: props.toolId,
        scrapBy: formValue.value.scrapBy,
        scrapName: formValue.value.scrapName,
        scrapReason: formValue.value.scrapReason,
        scrapRemark: formValue.value.scrapRemark,
        checkPic: checkPic,
        checkReportList: checkReportList
      };
      await scrapToolLedger(params);
      PxMessage.success("工具报废成功！");
      emits("closeDialog");
      emits("queryTable");
    }
  });
};
// 打开弹窗
const openDialog = async () => {
  formRef.value.resetFields();
  moduleName.value = await getModuleName({});
  scrapByList.value = await getEmployeeIdAndName();
  queryScrapReasonSelect();
};
// 查询列表关闭弹窗
const closeDialog = () => {
  emits("closeDialog");
};
</script>
<style lang="scss" scoped>
.tool-dialog-form {
  :deep(.px-form-item) {
    width: 720px;
    margin-bottom: 24px;

    .px-input {
      width: 100%;
    }

    .px-select {
      width: 100%;
    }

    .px-select-v2 {
      width: 100%;

      .px-select-v2__wrapper {
        cursor: pointer;
      }
    }
  }

  .tool-dialog-btns {
    :deep(.px-button + .px-button) {
      margin-left: 8px;
    }
  }
}
</style>
